/*
 * @Description: 
 * @Version: 2.0
 * @Autor: YouLiangxin
 * @Date: 2022-03-30 16:09:09
 * @LastEditors: VsCode
 * @LastEditTime: 2022-03-30 17:31:13
 */


/*
 * @Description: 
 * @Version: 2.0
 * @Autor: YouLiangxin
 * @Date: 2022-03-30 10:04:36
 * @LastEditors: VsCode
 * @LastEditTime: 2022-03-30 16:02:08
 */
var net = require('net');
var fs = require("fs");

var push_server = net.createServer();  // 创建 tcp server

var Sockets = {};
var SocketID = 1;

// 监听 端口
push_server.listen(5679, function () {
    console.log('上传服务监听 5679');
});

// 处理客户端连接
push_server.on('connection', function (socket) {
    console.log(socket.address());
    Sockets[SocketID] = socket;
    SocketID++;
    DealConnect(socket)
})

push_server.on('error', function () {
    console.log('上传服务 error!');
})

push_server.on('close', function () {
    console.log('上传服务 close!');
})

// 处理每个客户端消息
function DealConnect(socket) {
    var flag = false;
    var file_count = 0;
    var timer = null;
    var jsonstr = null;
    var buf = null;
    function time_Out() {
        console.log("上传服务 响应超时.");
        flag = false;
        file_count = 0;
    }

    socket.on('data', function (data) {
        if (flag == false) {
            try {
                jsonstr = JSON.parse(data);
                console.log("上传服务 文件头信息", jsonstr);

                //写配置文件
                fs.writeFileSync("config.ini", data)

                //建立缓冲区
                buf = Buffer.alloc(jsonstr.fileSize, 0,'binary');

                flag = true;
                timer = setTimeout(time_Out, 3000);
                socket.write("ok");
            } catch (e) { }
        }
        else {
            /*超时监测*/
            clearTimeout(timer);
            timer = setTimeout(time_Out, 3000);

            //写数据到缓冲区
            buf.write(data);

            file_count += data.length;
            
            if (file_count == jsonstr.fileSize) {
                console.log("文件接收完成", file_count)

                socket.write("ok");
                file_count = 0;
                flag = false;
                clearTimeout(timer);

            }
        }
    })
}
